package com.dx.aop;



import com.dx.annoation.AutoSet;
import com.dx.constants.AutoSetConstant;
import com.dx.context.ContextHolder;
import com.dx.enums.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Slf4j
@Aspect
public class AutoSetAop {

    @Pointcut("execution(* com.dx.mapper.*.*(..))&&@annotation(com.dx.annoation.AutoSet)")
    public void autoPoint(){}


    @Before("autoPoint()")
    public void autoSet(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("自动注入开始");
        Object[] args = joinPoint.getArgs();
        if (args.length==0){
            throw new RuntimeException("参数不能为空");
        }
        Object o=args[0];
        final Method setCreateTime = o.getClass().getDeclaredMethod(AutoSetConstant.SET_CREATED_TIME, LocalDateTime.class);
        final Method setUpdateTime = o.getClass().getDeclaredMethod(AutoSetConstant.SET_UPDATED_TIME, LocalDateTime.class);
        final Method setCreateUser = o.getClass().getDeclaredMethod(AutoSetConstant.SET_CREATED_USER, Long.class);
        final Method setUpdateUser = o.getClass().getDeclaredMethod(AutoSetConstant.SET_UPDATED_USER, Long.class);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoSet annotation = signature.getMethod().getAnnotation(AutoSet.class);
        OperationType operationType = annotation.value();
        switch (operationType) {
            case INSERT:
                log.info("插入操作");
                setCreateTime.invoke(o, LocalDateTime.now());
                setUpdateTime.invoke(o, LocalDateTime.now());
                setCreateUser.invoke(o, ContextHolder.getUser());
                setUpdateUser.invoke(o, ContextHolder.getUser().getId());
                break;
            case UPDATE:
                log.info("更新操作");
                setUpdateTime.invoke(o, LocalDateTime.now());
                setUpdateUser.invoke(o, ContextHolder.getUser().getId());
                break;
        }

        log.info("自动注入结束");
    }
}
